#ifndef NETWORK_MANAGER_H
#define NETWORK_MANAGER_H

#include <QMap>
#include <QList>
#include <QObject>
#include <QSemaphore>
#include <QThread>
#include <QVariant>


class QNetworkAccessManager;
namespace Network {
class Connection;
class Request;
class ConnectionRequest;
class Parser;
class Event;
class Manager : public QObject
{
    Q_OBJECT
protected:
    Manager(QObject *parent = 0);
    
public:
    static Manager *instance(QObject *parent = 0);

    inline static void setServer(const QString &server) {
        m_server = server;
    }

    inline static const QString &server() {
        return m_server;
    }

    inline static void setPort(int port) {
        m_port = port;
    }

    inline static int port() {
        return m_port;
    }

public:
    inline QNetworkAccessManager &networkAccessManager() {
        return *m_networkAccessManager;
    }

    inline Connection &connection() {
        return *m_connection;
    }

    inline const QString &sessionKey() const {
        return m_sessionKey;
    }

public:
    bool post(Request *request);
    void stop();

signals:
    void connected();
    void received(const QString &commandId, const QVariant &data);
    void disconnected();
    void sessionKeyReady();

private slots:
    void onLogined(bool successed, const QString &message, const QString &sessionKey);
    void onConnected();
    void onReceived(QByteArray message);
    void onDisconnected();
    void onLogouted();

private:
    virtual QVariant params() const = 0;
    void setConnection() const;
    void logout();

private:
    Connection *m_connection;
    QNetworkAccessManager *m_networkAccessManager;
    QString m_sessionKey;

private:
    static Manager *m_instance;
    static QString m_server;
    static int m_port;
};

} // namespace Network
#endif // NETWORK_MANAGER_H
